const decrypt = require('./libs/decrypt');
const { makeRequest } = require('./libs/gotRequest');
/**
 * 豆瓣图书搜索
 * @param {搜索关键字} text 
 * @returns 
 */
async function getSearchResultFromOnline(text) {
  try {
    const response = await makeRequest('https://search.douban.com/book/subject_search?search_text=' + text);
    const r = /window\.__DATA__ = "(.*?)";/.exec(response)[1];
    const result = decrypt(r);
    return result.payload.items;
  } catch (error) {
    throw new Error('getSearchResultFromOnline throws exception.',error);
  }
}

/**
 * 电影演员关键字搜索
 * @param {搜索关键字} text 
 * @param {分页开始} start 
 * @returns 
 */
async function getSearchResultFromOnlineMovie(text, start = 0) {
  try {
    const response = await makeRequest(`https://search.douban.com/movie/subject_search?search_text=${text}&cat=1002&start=${start}`);

    // const match = /window\.__DATA__ = "(.*?)";/.exec(response);
    const match = /window\.__DATA__\s*=\s*(\{.*?\});/.exec(response);

    if (!match) {
      throw new Error('No matching data found in the response.');
    }
    if (match && match[1]) {
      const data = JSON.parse(match[1]);
      console.log(data);  // 这里可以输出或处理解析后的数据
      return data.items;
    }  
    return null;
    // const encryptedData = match[1];
    // const result = decrypt(encryptedData);
    // return result.payload.items;
  } catch (error) {
    console.error('Error in getSearchResultFromOnlineMovie:', error);
    throw new Error('getSearchResultFromOnlineMovie throws exception.', error);
  }
}


module.exports = {
  getSearchResultFromOnline,
  getSearchResultFromOnlineMovie
};
